package com.example8.fenku_fenbiao2.algorithm;

import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shardingsphere.sharding.api.sharding.standard.PreciseShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.RangeShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.StandardShardingAlgorithm;
import org.springframework.beans.factory.annotation.Value;

import java.util.Collection;
import java.util.Properties;

/**
 * @description sharding jdbc 精准`分表`策略
 **/
@Slf4j
public class PreciseShardingTableAlgorithm implements StandardShardingAlgorithm<String> {

    // 分表数量
    private static int tableSize;

    @Value("${tableSize: 1}")
    public void setTableSize(int size) {
        tableSize = size;
    }

    /**
     * @description: 分表策略，按用户编号倒数二三位数字对数据库表数量取模
     *
     * @param tableNames 所有表名
     * @param preciseShardingValue 精确分片值，包括（columnName，logicTableName，value）
     * @return 表名
     */
    @Override
    public String doSharding(Collection<String> tableNames, PreciseShardingValue<String> preciseShardingValue) {

        log.info("Table PreciseShardingAlgorithm tableNames:{} ,preciseShardingValue: {}.",
                JSON.toJSONString(tableNames), JSON.toJSONString(preciseShardingValue));
        // 按表数量取模
        // 截取用户编号倒数二三位数字，（如1234的倒数二三位为23）
        String num = StringUtils.substring(preciseShardingValue.getValue(), -3, -1);
        int mod = Integer.parseInt(num) % tableSize;
        for (String tableName : tableNames) {
            // 分表的规则
            if (tableName.endsWith(String.valueOf(mod))) {
                return tableName;
            }
        }
        throw new UnsupportedOperationException();
    }

    @Override
    public Collection<String> doSharding(Collection<String> collection, RangeShardingValue<String> rangeShardingValue) {
        return null;
    }


    public Properties getProps() {
        return null;
    }


    public void init(Properties properties) {

    }
}
